package me.shurufa.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.NewLoginActivity;
import me.shurufa.activities.NewUserCenterActivity;
import me.shurufa.activities.PhotoViewManager;
import me.shurufa.activities.ShareEditActivity;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.holder.BaseViewHolder;
import me.shurufa.model.NewComment;
import me.shurufa.model.NewDigest;
import me.shurufa.model.UserInfoEntity;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Settings;
import me.shurufa.utils.Utils;
import me.shurufa.widget.animutils.AnimOnTouchListener;

/**
 * 作者 : andy
 * 日期 : 16/3/8 14:50
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 书摘列表适配器
 */
public class BookDigestMeAdapter extends RecyclerView.Adapter<BookDigestMeAdapter.DigestHolder> {
    private Context mContext;
    private List<NewDigest> mDatas;
    private OnOperateClickListener mOnOperateClickListener;

    private int mWhereFrom;
    private String mBookname;

    private SparseBooleanArray mNoteExpandState = new SparseBooleanArray();    // 笔记展开的状态  默认false
    private SparseBooleanArray mCommentExpandState = new SparseBooleanArray(); // 评论展开的状态  默认false

    public BookDigestMeAdapter(Context context, String bookname, List<NewDigest> datas, int whereFrom) {
        this.mDatas = datas;
        mContext = context;
        this.mWhereFrom = whereFrom;
        this.mBookname = bookname;
    }

    @Override
    public DigestHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (Constants.DIGEST_TYPE_IMAGE == viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_bookdetail_digest_me_type_img, parent, false);
            return new DigestHolder(v);
        }

        if (Constants.DIGEST_TYPE_TEXT == viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_bookdetail_digest_me, parent, false);
            return new DigestHolder(v);
        }

        // default
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_bookdetail_digest_me, parent, false);
        return new DigestHolder(v);
    }

    @Override
    public int getItemViewType(int position) {
        NewDigest digest = mDatas.get(position);
        return digest.getType();
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    @Override
    public void onBindViewHolder(final DigestHolder holder, final int position) {
        try {
            bindData(holder, position);
            bindListener(holder, position);
        } catch (Exception e) {
            e.printStackTrace();
            Utils.showToast(R.string.sys_err);
        }
    }

    private void bindData(DigestHolder holder, int position) {
        // 书摘
        NewDigest digest = mDatas.get(position);
        if (Constants.DIGEST_TYPE_TEXT == digest.getType()) {
            holder.iv_digest_content.setVisibility(View.GONE);
            holder.tv_digest_content.setVisibility(View.VISIBLE);
            holder.tv_digest_content.setText(digest.getContent());
        } else {
            holder.tv_digest_content.setVisibility(View.GONE);
            holder.iv_digest_content.setVisibility(View.VISIBLE);
            // 图片书摘
            Glide.with(mContext).load(digest.getScreenshot() + Constants.THUMB_SUFFIX).centerCrop()
                    .placeholder(R.drawable.ic_placeholder_digest_image).error(R.drawable.ic_placeholder_digest_image).into(holder.iv_digest_content);
        }

        // 用户
        UserInfoEntity user_info = digest.getUser_info();
        holder.tv_mark_user.setText(user_info.getNickname());

        // 笔记
        NewDigest.MenuInfoEntity menu_info = digest.getMenu_info();
        holder.tv_chapter.setText(mContext.getString(R.string.chapter_suffix) + (TextUtils.isEmpty(menu_info.getTitle()) ? mContext.getString(R.string.no_chapter_info) : menu_info.getTitle()));
        holder.tv_chapter.setVisibility(TextUtils.isEmpty(menu_info.getTitle()) ? View.INVISIBLE : View.VISIBLE);
        holder.tv_mark_content.setText(digest.getNote());
        holder.tv_note_create_time.setText(Utils.getFormatTime(digest.getCreated_at()));
        // 若无笔记内容，则显示暂无笔记
        boolean hasNote = !TextUtils.isEmpty(digest.getNote());
        holder.tv_mark_content.setVisibility(hasNote ? View.VISIBLE : View.GONE);
        holder.tv_no_note.setVisibility(hasNote ? View.GONE : View.VISIBLE);

        // 页数
        holder.tv_page_no.setText("P." + digest.getPage_num());
        holder.tv_page_no.setVisibility((TextUtils.isEmpty(digest.getPage_num()) || "0".equals(digest.getPage_num())) ? View.INVISIBLE : View.VISIBLE);

        // 四个操作按钮
        boolean isZero = TextUtils.isEmpty(digest.getZan_num()) || "0".equals(digest.getZan_num());
        try {
            int praiseNum = Integer.parseInt(digest.getZan_num());
            if (praiseNum <= 0) {
                isZero = true;
            }
        } catch (NumberFormatException e) {
        }
        holder.tv_praise_num.setText(isZero ? null : digest.getZan_num());
        String commentNum = Utils.isNullForList(digest.getComments()) ? "" : digest.getComments().size()+ "";
        holder.tv_comment_num.setText(commentNum);

        if (null != digest.collect_info) {
            NewDigest.CollectInfoEntity collectInfo = digest.collect_info;
            boolean favorite = collectInfo.favorite;
            boolean praise = collectInfo.plusone;
            holder.tv_praise.setBackgroundResource(praise ? R.drawable.ic_praise_selected : R.drawable.ic_praise_normal);
        }


        bindCommentData(holder, position);

        boolean isNoteExpand = mNoteExpandState.get(position);
        holder.expand_view.setImageResource(isNoteExpand ? R.drawable.ic_arrow_top : R.drawable.ic_arrow_bottom);
        holder.layout_mark_content.setVisibility(mNoteExpandState.get(position) ? View.VISIBLE : View.GONE);
        holder.expand_comment_layout.setVisibility(mCommentExpandState.get(position) ? View.VISIBLE : View.GONE);
    }


    /**
     * 绑定评论数据
     * @param holder
     * @param position
     */
    private void bindCommentData(DigestHolder holder, final int position) {
        final NewDigest digest = mDatas.get(position);
        List<NewComment> comments = digest.getComments();
        if (!Utils.isNullForList(comments)) {
            holder.comment_container.removeAllViews();
            for (int i = 0; i < comments.size(); i ++) {

                final NewComment comment = comments.get(i);
                final int childPosition = i;
                View commentChild = View.inflate(mContext, R.layout.item_comment, null);
                TextView tv_uname = (TextView) commentChild.findViewById(R.id.tv_uname);
                final ImageView iv_avatar = (ImageView) commentChild.findViewById(R.id.iv_avatar);
                TextView tv_create_time = (TextView) commentChild.findViewById(R.id.tv_create_time);
                TextView tv_comment_content = (TextView) commentChild.findViewById(R.id.tv_comment_content);
                TextView btn_reply = (TextView) commentChild.findViewById(R.id.btn_reply);
                View divider = commentChild.findViewById(R.id.divider);
                divider.setVisibility(i == comments.size() - 1 ? View.INVISIBLE : View.VISIBLE);

                // username
                tv_uname.setText(comment.getUser_info().getNickname());
                // 时间
                tv_create_time.setText(Utils.getFormatTime(comment.getCreated_at()));
                tv_comment_content.setText(comment.getContent());

                btn_reply.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (null != mOnOperateClickListener) {
                            mOnOperateClickListener.onReplyCommentClick(v, position, childPosition, digest);
                        }
                    }
                });

                // avatar
                Glide.with(mContext).load(comment.getUser_info().getAvatar() + Constants.THUMB_SUFFIX_AVATAR).asBitmap().centerCrop().into(new BitmapImageViewTarget(iv_avatar) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        super.setResource(resource);
                        RoundedBitmapDrawable circularBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(mContext.getResources(), resource);
                        circularBitmapDrawable.setCircular(true);
                        iv_avatar.setImageDrawable(circularBitmapDrawable);
                    }
                });
                holder.comment_container.addView(commentChild);
            }
        }
    }

    private void bindListener(final DigestHolder holder, final int position) {
        holder.btn_praise.setOnTouchListener(new AnimOnTouchListener());
        holder.btn_del.setOnTouchListener(new AnimOnTouchListener());
        holder.btn_edit.setOnTouchListener(new AnimOnTouchListener());
        holder.btn_comment.setOnTouchListener(new AnimOnTouchListener());
        holder.btn_share.setOnTouchListener(new AnimOnTouchListener());

        final NewDigest digest = mDatas.get(position);

        // 昵称点击 进入用户详情界面
        if (Constants.FROM_USER_CENTER != mWhereFrom) {
            holder.tv_mark_user.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent in = new Intent(mContext, NewUserCenterActivity.class);
                    //NewUserCenterActivity.initArguments(in, digest.getUser_info(), true);
                    mContext.startActivity(in);
                }
            });
        }

        // 进入到分享界面
        holder.btn_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent in = new Intent(mContext, ShareEditActivity.class);
                //ShareEditActivity.initArguments(in, mBookname, digest, null);
                mContext.startActivity(in);
            }
        });

        // 点击图片书摘 查看大图
        holder.iv_digest_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhotoViewManager.loadImage(mContext, digest.getScreenshot());
            }
        });

        // 点击编辑
        holder.btn_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnOperateClickListener != null) {
                    mOnOperateClickListener.onEdit(position, digest);
                }
            }
        });

        // 点击删除
        holder.btn_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnOperateClickListener != null) {
                    mOnOperateClickListener.onDel(position, digest);
                }
            }
        });


        // 点击评论
        holder.btn_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 回调
                if (mOnOperateClickListener != null) {
                    mOnOperateClickListener.onCommentClick(v, position, digest);
                }

                // 若已经展开  则不再执行再展开
                if (holder.expand_comment_layout.getVisibility() == View.VISIBLE) {
                    return;
                }

                // 若还没有评论 则不展开
                if (Utils.isNullForList(digest.getComments())) {
                    return;
                }

                // 展开状态取反
                boolean isCommentExpand = mCommentExpandState.get(position);
                mCommentExpandState.put(position, !isCommentExpand);

                // 开关
                holder.expand_comment_layout.setVisibility(isCommentExpand ? View.GONE : View.VISIBLE);
            }
        });

        // 点击箭头展开/收回笔记
        holder.expand_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isNoteExpand = mNoteExpandState.get(position);
                holder.layout_mark_content.setVisibility(isNoteExpand ? View.GONE : View.VISIBLE);
                holder.expand_view.setImageResource(!isNoteExpand ? R.drawable.ic_arrow_top : R.drawable.ic_arrow_bottom);
                mNoteExpandState.put(position, !isNoteExpand);
            }
        });


        // 点击评论底部的收回按钮 收缩评论内容
        holder.ll_collapse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                holder.expand_comment_layout.setVisibility(View.GONE);
                mCommentExpandState.put(position, false);
            }
        });

        final NewDigest.CollectInfoEntity collectInfo = digest.collect_info;
        // 点击点赞
        holder.btn_praise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == collectInfo) {
                    return;
                }
                if (null != mOnOperateClickListener) {
                    mOnOperateClickListener.onPraiseClick(!collectInfo.plusone, digest);
                }
            }
        });
    }

    public class DigestHolder extends BaseViewHolder {
        @Bind(R.id.tv_digest_content)
        TextView tv_digest_content;
        @Bind(R.id.iv_digest_content)
        ImageView iv_digest_content;
        @Bind(R.id.tv_mark_user)
        TextView tv_mark_user;
        @Bind(R.id.tv_mark_content)
        TextView tv_mark_content;

        @Bind(R.id.ll_praise)
        LinearLayout btn_praise;
        @Bind(R.id.ll_edit)
        LinearLayout btn_edit;
        @Bind(R.id.ll_del)
        LinearLayout btn_del;
        @Bind(R.id.tv_praise_num)
        TextView tv_praise_num;
        @Bind(R.id.tv_comment_num)
        TextView tv_comment_num;

        @Bind(R.id.tv_praise)
        TextView tv_praise;
        @Bind(R.id.ll_share)
        LinearLayout btn_share;
        @Bind(R.id.ll_comment)
        LinearLayout btn_comment;

        @Bind(R.id.expand_view)
        ImageView expand_view;
        @Bind(R.id.ll_collapse)
        LinearLayout ll_collapse;
        @Bind(R.id.expand_comment_layout)
        LinearLayout expand_comment_layout;

        @Bind(R.id.layout_mark_content)
        LinearLayout layout_mark_content;
        @Bind(R.id.comment_container)
        LinearLayout comment_container;

        @Bind(R.id.tv_chapter)
        TextView tv_chapter;
        @Bind(R.id.tv_page_no)
        TextView tv_page_no;
        @Bind(R.id.tv_note_create_time)
        TextView tv_note_create_time;

        @Bind(R.id.tv_no_note)
        TextView tv_no_note;


        public DigestHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

    public void setOnOperateClickListener(OnOperateClickListener l) {
        this.mOnOperateClickListener = l;
    }

    /**
     * 操作按钮点击接口
     */
    public interface OnOperateClickListener {
        /**
         * 点击评论
         * @param v
         * @param position
         * @param digest
         */
        void onCommentClick(View v, int position, NewDigest digest);

        /**
         * 点击回复
         * @param v
         * @param parentPosition
         * @param childPosition
         * @param digest
         */
        void onReplyCommentClick(View v, int parentPosition, int childPosition, NewDigest digest);

        /**
         * 点击点赞按钮
         * @param prePraise
         * @param digest     true: 点赞   false: 取消点赞
         */
        void onPraiseClick(boolean prePraise, NewDigest digest);

        /**
         * 编辑书摘的回调
         * @param position
         * @param digest
         */
        void onEdit(int position, NewDigest digest);

        /**
         * 删除书摘的回调
         * @param position
         * @param digest
         */
        void onDel(int position, NewDigest digest);

    }

    public void append(NewDigest[] items) {
        int pos = mDatas.size();
        for (NewDigest item : items) {
            if (!mDatas.contains(item)) {
                mDatas.add(item);
                mNoteExpandState.append(mDatas.size() - 1, false);
                mCommentExpandState.append(mDatas.size() - 1, false);
            }
        }
        notifyItemRangeInserted(pos, items.length);
    }

    public void clear() {
        int size = mDatas.size();
        mDatas.clear();
        mNoteExpandState.clear();
        mCommentExpandState.clear();
        this.notifyItemRangeRemoved(0, size);
    }

    private boolean handleLoginClick() {
        boolean isLogin = PersistenceUtils.isLogin();
        Intent in = null;
        // 已登录 跳转到ProfileActivity
        if (isLogin) {
            return true;
        }

        // 未登录 则跳转至登录界面，点击登录时需要返回到当前界面
        else {
            in = new Intent(mContext, NewLoginActivity.class);
            in.setAction(Constants.ACTION_GO_LOGIN);
            EventBus.getDefault().postSticky(in);
            //mContext.startActivity(in);
            return false;
        }
    }
}
